<template>
  <div>
    <t-card class="list-card-container" :bordered="false">
      <t-row justify="space-between">
        <div class="left-operation-container">
          <t-button @click="handleCreateScene"> 新增任务 </t-button>
          <t-button
            variant="base"
            theme="default"
            :disabled="!selectedRowKeys.length"
          >
            导出任务
          </t-button>
          <p v-if="!!selectedRowKeys.length" class="selected-count">
            已选{{ selectedRowKeys.length }}项
          </p>
        </div>
        <t-input
          v-model="searchValue"
          class="search-input"
          placeholder="请输入你需要搜索的内容"
          clearable
        >
          <template #suffix-icon>
            <search-icon size="20px" />
          </template>
        </t-input>
      </t-row>

      <div class="table-container">
        <t-table
          :columns="columns"
          :data="data"
          :rowKey="rowKey"
          :verticalAlign="verticalAlign"
          :hover="hover"
          :pagination="pagination"
          :selected-row-keys="selectedRowKeys"
          :loading="dataLoading"
          @page-change="rehandlePageChange"
          @change="rehandleChange"
          @select-change="rehandleSelectChange"
          :headerAffixedTop="true"
          :headerAffixProps="{ offsetTop: offsetTop, container: getContainer }"
        >
          <template #status="{ row }">
            <t-tag
              v-if="row.status === CHAIN_STATUS.CONN_FAIL"
              theme="danger"
              variant="light"
              >连接异常</t-tag
            >
            <t-tag
              v-if="row.status === CHAIN_STATUS.CONN_INIT"
              theme="warning"
              variant="light"
              >未连接</t-tag
            >
            <t-tag
              v-if="row.status === CHAIN_STATUS.CONN_SUCCESS"
              theme="success"
              variant="light"
              >运行中</t-tag
            >
          </template>
          <template #client_type="{ row }">
            <p v-if="row.client_type === 0">cmc</p>
            <p v-if="row.client_type === 1">go-sdk</p>
            <p v-if="row.client_type === 2">java-sdk</p>
          </template>
          <template #contract_type="{ row }">
            <p v-if="row.contract_type === 0">系统合约</p>
            <p v-if="row.contract_type === 1">用户合约</p>
          </template>

          <template #op="slotProps">
            <a class="t-button-link" @click="handleClickApply(slotProps)">分析</a>
            <a class="t-button-link" @click="handleClickDetail(slotProps)">详情</a>
            <a class="t-button-link" @click="handleClickDelete(slotProps)">删除</a>
          </template>
        </t-table>
      </div>
    </t-card>
    <t-dialog
      :visible.sync="confirmVisible1"
      @confirm="handleConfirmApply"
    ><!-- @confirm="confirmVisible1 = false" -->
      <p>确认执行此场景？</p>
    </t-dialog>
    <t-dialog
      header="确认删除当前所选链？"
      :body="confirmBody"
      :visible.sync="confirmVisible"
      @confirm="onConfirmDelete"
      :onCancel="onCancel"
    >
    </t-dialog>
    <modify
      v-if="showDialogModify"
      :show-child-dialog.sync="showDialogModify"
      ref="dialogmodify"
    />
  </div>
</template>
<script lang="ts">
import Vue from "vue";
import { SearchIcon } from "tdesign-icons-vue";
//   import Trend from '@/components/trend/index.vue';
//   import { prefix } from '@/config/global';

import { CHAIN_STATUS, AUTH_TYPE_STATUS, CONSENSUS_TYPE } from "@/constants";
import modify from "./components/modify2.vue";

export default Vue.extend({
  name: "ListBase",
  components: {
    SearchIcon,
    modify,
  },
  data() {
    return {
      CHAIN_STATUS,
      AUTH_TYPE_STATUS,
      CONSENSUS_TYPE,
      // CONTRACT_PAYMENT_TYPES,
      // prefix,
      dataLoading: false,
      data: [],
      selectedRowKeys: [1, 2],
      value: "first",
      columns: [
        { colKey: "row-select", type: "multiple", width: 34, fixed: "left" },
        {
          title: "id",
          align: "left",
          width: 50,
          ellipsis: true,
          colKey: "id",
          fixed: "left",
        },
        {
          title: "场景",
          align: "left",
          width: 150,
          ellipsis: true,
          colKey: "scenario_id",
          fixed: "left",
        },
        {
          title: "链配置",
          colKey: "chain_type_id",
          width: 100,
          // cell: { col: 'status' }
        },
        {
          title: "创建时间",
          width: 100,
          ellipsis: true,
          colKey: "create_time",
        },
        {
          align: "left",
          fixed: "right",
          width: 200,
          colKey: "op",
          title: "操作",
        },
      ],
      rowKey: "index",
      tableLayout: "auto",
      verticalAlign: "top",
      hover: true,
      rowClassName: (rowKey: string) => `${rowKey}-class`,
      // 与pagination对齐
      pagination: {
        defaultPageSize: 100,
        total: 100,
        defaultCurrent: 1,
      },
      searchValue: "",
      confirmVisible: false,
      deleteIdx: -1,
      confirmVisible1: false,
      showDialogModify: false,
    };
  },
  computed: {
    showDialog: {
      get() {
        return this.showChildDialog;
      },
      set(newValue) {
        this.$emit("update:showChildDialog", newValue); // 触发更新事件，父组件的showDialogAdd会自动更新
      },
    },
    confirmBody() {
      if (this.deleteIdx > -1) {
        const { name } = this.data?.[this.deleteIdx];
        return `删除后，${name}的所有链信息将被清空，且无法恢复`;
      }
      return "";
    },
    offsetTop() {
      return this.$store.state.setting.isUseTabsRouter ? 48 : 0;
    },
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.dataLoading = true;
      const params = {
        params: {
          page: this.pagination.defaultCurrent,
          per_page: this.pagination.defaultPageSize,
        },
      };
      this.$request
        .get("/api/performance/task/list", params)
        .then((res) => {
          if (res.status === 200) {
            console.log("请求成功：", res.data);
            const { task_list = [], total = 0 } = res.data;
            this.data = task_list;
            // console.log('data', this.data);
            this.pagination = {
              ...this.pagination,
            };
          }
        })
        .catch((e: Error) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    handleClickDetail(slotProps) {
      const chain_type_id = slotProps.row.id;
      console.log("详情页----", slotProps.row.id);
      const params = {
        params: {
          task_id: slotProps.row.id,
        },
      };
      this.$request
        .get("/api/performance/task/details", params)
        .then((res) => {
          if (res.status === 200) {
            console.log("task details请求成功：", res.data);
            // const { chain_config_details, scenario_config_details } = res.data;
            // console.log("task chain_config_details", chain_config_details);
            // console.log("task scenario_config_details", scenario_config_details);
            
            this.showDialogModify = true;
            this.$nextTick(() => {
              this.$refs.dialogmodify.init(res.data);
            });
          }
        })
        .catch((e: Error) => {
          console.log(e);
        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
    

    getContainer() {
      return document.querySelector(".tdesign-starter-layout");
    },
    rehandlePageChange(curr, pageInfo) {
      console.log("分页变化", curr, pageInfo);
      this.pagination.current = pageInfo.current;
      this.pagination.pageSize = pageInfo.pageSize;
      this.fetchData();
    },
    rehandleSelectChange(selectedRowKeys: number[]) {
      this.selectedRowKeys = selectedRowKeys;
    },
    rehandleChange(changeParams, triggerAndData) {
      console.log("统一Change", changeParams, triggerAndData);
    },
    handleCreateScene() {
      this.$router.push('/scene/add');
    },
    handleClickDelete(row: { rowIndex: any }) {
      this.deleteIdx = row.rowIndex;
      this.confirmVisible = true;
    },
    onConfirmDelete() {
      // 真实业务请发起请求
      this.data.splice(this.deleteIdx, 1);
      this.pagination.total = this.data.length;
      const selectedIdx = this.selectedRowKeys.indexOf(this.deleteIdx);
      if (selectedIdx > -1) {
        this.selectedRowKeys.splice(selectedIdx, 1);
      }
      this.confirmVisible = false;
      this.$message.success("删除成功");
      this.resetIdx();
    },
    onCancel() {
      this.resetIdx();
    },
    resetIdx() {
      this.deleteIdx = -1;
    },
    // 执行场景
    handleClickApply(slotProps) {

      this.confirmVisible1 = true;
      this.currentId = slotProps.row.id;
      console.log("执行场景，id：", this.currentId);

    },
    handleConfirmApply() {
    
      this.$request
        .post(`/api/performance/scenario/genenv?scenario_id=${this.currentId}`)
        .then((res) => {
          if (res.status === 200) {
            console.log("场景执行：", res.data);
            this.confirmVisible1 = false;
            this.$message.success('场景执行成功');
          }
        })
        .catch((e: Error) => {
          console.log(e);
          this.$message.fail(e);

        })
        .finally(() => {
          this.dataLoading = false;
        });
    },
  },
});
</script>

<style lang="less" scoped>
@import "@/style/variables";

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: 8px;
  }
}
.auto-width {
  min-width: 100px;
  max-width: 300px;
}

.left-operation-container {
  padding: 0 0 6px 0;
  margin-bottom: 16px;

  .selected-count {
    display: inline-block;
    margin-left: var(--td-comp-margin-s);
    color: var(--td-text-color-secondary);
  }
}

.search-input {
  width: 360px;
}

.t-button + .t-button {
  margin-left: var(--td-comp-margin-s);
}
</style>
